import 'dart:io';

import 'package:qiniu_flutter_sdk/qiniu_flutter_sdk.dart';
import 'package:xws/models/res_obj.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/dio_utils/request_apis.dart';
import 'package:xws/utils/dio_utils/request_source.dart';
import 'package:xws/utils/log_util.dart';

enum Dir { head, goods, feedback, chat }

extension _ExDir on Dir {
  String get dir {
    switch (this) {
      case Dir.head:
        return 'head/';
      case Dir.goods:
        return 'goods/';
      case Dir.feedback:
        return 'feedback/';
      case Dir.chat:
        return 'chat/';
      default:
        return '';
    }
  }
}

/// 七牛云oss封装
class QiniuOSS {
  const QiniuOSS._();

  /// 最后一次获取token的时间，两分钟内不会重复获取
  static DateTime? _last;

  /// bucket
  static const String bucket = 'earthangel';

  /// host
  static const String host = 'https://oss.tianshi.guangguang100.com/';

  /// token
  static String _token = '';

  /// 上传多个文件
  static Future<List<String>> uploadFiles(List<String> files, Dir d) async {
    try {
      final String token = await _getToken();

      if (token.isEmpty) return <String>[];

      final Storage storage = Storage();

      final List<String> pathList = <String>[];

      for (final String f in files) {
        /// 上传完成的图片
        if (f.startsWith('http')) {
          pathList.add(f);
          continue;
        }

        final String k = d.dir + f.split('/').last;

        final PutResponse pr = await storage.putFile(
          File(f),
          token,
          options: PutOptions(
            maxPartsRequestNumber: 1,
            customVars: <String, String>{'key': k},
          ),
        );

        if (pr.key != null) pathList.add(host + pr.key!);
      }

      return pathList;
    } catch (e) {
      error('上传多个文件出错:$e');
      _token = '';
      return <String>[];
    }
  }

  /// 删除文件
  static Future<bool> delFile(String file, Dir d) async {
    try {
      final String token = await _getToken();

      if (token.isEmpty) return false;

      // final Storage storage = Storage();

      /// 删除文件

      return true;
    } catch (e) {
      error('删除文件出错:$e');
      _token = '';
      return false;
    }
  }

  /// 从后台获取上传凭据
  static Future<String> _getToken() async {
    try {
      if (_token.isNotEmpty && _last != null && DateTime.now().difference(_last!).inMinutes < 2) {
        return _token;
      }

      _last = DateTime.now();

      final ResObj? res = await getObj<ResObj>(
        APIS.qiniuToken,
        method: 'get',
      );

      if (res == null || !res.success) {
        ct(res?.message ?? '网络错误');
        return '';
      }

      _token = res.data.toString();

      return _token;
    } catch (e) {
      error('从后台获取上传凭据出错:$e');
      return '';
    }
  }
}
